/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * Created by ued on 2016/10/31.
 */

// 所有页面的总入口

import 'babel-polyfill';
import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

Vue.config.devtools = true;

import Vuex from 'vuex';
import VueRouter from 'vue-router';

/* eslint-disable */
// import SFVueComponent from './sfv';
import {
    setStorage
} from 'src/util/local_storage';
import {
    USER_ID,
    USER_ROLE
} from 'src/home/mod_common/const';
import {IS_ADMIN, USERS_ID} from 'src/vuex/mutation_types';

// import '@sxf/sf-vue-component/dist/theme/cloud.css';
import initTheme from 'src/theme/index';

import Language from 'src/i18n/index';
import VTypes from 'src/util/vtypes/vtypes';
import * as Ajax from 'src/util/ajax';
import store from 'src/vuex/store';

import routes from './router_config';
import AppNav from './nav';

import beforeInit from './before_init';
// import AppFooter from './footer/footer.vue';
import * as IntervalTask from './interval_task/index';
import {
    isFunction
} from 'src/util/typeof';
import {
    on as bindEvent
} from 'wind-dom';
import {
    debounce
} from 'src/util/delay';
import 'src/home/mod_common/style/common.css'; // 公共样式表

import 'src/home/mod_common/style/media.css'; // 媒体查询样式表
import 'src/home/mod_common/style/media_less.less'; // 媒体查询样式表(引用less)
import 'src/home/mod_common/style/iconfont_theme.css'; // iconfont图标样式表
import 'src/home/mod_common/style/abdi_common.less'; //abdi项目公共样式
import 'src/home/mod_common/style/ai_common.less'; //AI平台项目公共样式
import 'src/home/mod_common/style/box.less'; //公共盒模型样式
import 'src/home/mod_common/style/color.less'; //颜色样式
import 'src/home/mod_common/style/sf_theme.less'; // 替换组件库部分样式
import './element';
import 'element-ui/lib/theme-chalk/index.css';
import uploader from 'vue-simple-uploader'
import VueCompositionApi from  '@vue/composition-api'

Vue.use(uploader)
Vue.use(VueCompositionApi)

// copy 的插件
import VueClipboard from 'vue-clipboard2';

Vue.use(VueClipboard);
import MultiLineHide from 'src/home/mod_common/directive/multi_line'; //加载自定义指令 多行文本超出隐藏
import DatasourceManagerIframe from 'src/home/mod_cluster/datasource_manager/index.vue';
import extFramework from '@uedc/ext-framework';

if (process.env.NODE_ENV === 'development') {
    initTheme();
}

extFramework.initFramework({
    lang: 'en'
});

MultiLineHide.init();

Vue.config.devtools = true;

// 地址上配置 ?lang=en_US 开启英文模式
let lang = location.search.match(/lang=(\w+)/);

if (lang) {
    window.SHARED.lang = lang[1];
}

let i18n = {
    lang: window.SHARED.lang
};

Vue.use(Vuex);

// 初始化路由
Vue.use(VueRouter);


// 初始化上传模块
// Vue.use(uploader);

// 初始化i18n
Vue.use(Language, i18n);

Vue.use(VTypes);


let router;
let app;

let activeTab = '/home';

/* eslint-disable */
// const TOKEN_TIME = 10 * 60  * 1000;
// import IntervalTasks from 'src/util/interval_task';

/**
 * 初始化页面路由
 * @return {VueRouter} 返回路由
 */
function initRouter() {
    router = new VueRouter({
        routes
    });

    // 当前无导航, 注释掉这里导航选中tab高亮的处理.后面有导航了再加回来.
    router.beforeEach((to, form, next) => {

        // 1、路由匹配不上
        // 2、子路由只提取根路径，高亮导航条
        let match = to.path.match(/^(\/[^\/]+).*/);
        if (!to.matched || !to.matched.length || !match) {
            next(`${activeTab}`);
            return;
        }

        activeTab = match[1];
        if (app) {
            app.activeTab = activeTab;
        }
        next();
    });
    return router;
}

/**
 * 加载主页面
 */

/* eslint-disable */

function initApp() {
    let indexScreenList = [/^#\/index/i];
    let checkIsIndexScreen = () => !!indexScreenList.find((reg) => reg.test(window.location.hash));

    app = new Vue({
        data() {
            return {
                activeTab: activeTab,
                isIndexScreen: true,
                bodyHeight: 'calc(100vh - 60px)',
                intervalTasks: null
            };
        },
        computed: {
            isShowWarn() {
                return this.$store.state.authorization.isShowAuthWarn;
            },
            opaClsObj() {
                return {
                    'lang-en': i18n.lang === 'en_US',
                    'show-expiration-warning': this.isShowWarn
                };
            }
        },
        router,
        store,
        template: `
            <div id="opa" :class="opaClsObj" class="mainApp" ref="mainApp">
            <app-nav ref="navComp" :active-tab="activeTab"/>
            <div id="body">
                <keep-alive v-if="$route.name !== 'datasource_manager'">
                    <router-view v-if="$route.meta.keepAlive"
                                 ref="viewComp"/>
                </keep-alive>
                <router-view v-if="!$route.meta.keepAlive && $route.name !== 'datasource_manager'"
                             ref="viewComp"/>
                <datasource-manager-iframe v-show="$route.name === 'datasource_manager'"
                                           ref="viewComp"></datasource-manager-iframe>
                <!-- app-footer v-if="!isIndexScreen" /-->
            </div>
            </div>
        `,
        // :class="{maintain: isIndexScreen}"
        components: {
            AppNav,
            DatasourceManagerIframe
            // AppFooter
        },
        watch: {
            '$route.path'() {
                this.isIndexScreen = checkIsIndexScreen();
            }
        },
        beforeMount() {
            this.getUserInfo();
        },
        async created() {
            if (location.hash === "#/") {
                return this.$router.replace({
                    path: `${activeTab}`,
                });
            }
        },
        methods: {
            getUserInfo() {
                let vm = new Vue();
                vm.$ajax.get('/auth/v1/user/loginInfo').then((jsonData) => {
                    let data = jsonData.data;
                    if (data) {
                        //userId
                        setStorage(USER_ID, data && data.userId);
                        //是否为管理员
                        setStorage(USER_ROLE, data && data.role);
                        setStorage('token', data && data.s3Token);
                        store.commit(USERS_ID, data.userId);
                        store.commit(IS_ADMIN, !!data.role);
                    }

                })
            }
        },
    });

    app.$mount('#app');

    window.SHARED.$root = app;

    app.$store.commit('updateHeight', app.isShowWarn);
    app.$store.commit('updateWidth');
    app.$store.commit('updateLeftNavWidth');

    // 一些公共的定时任务处理
    IntervalTask.run();

}

/**
 * 绑定 resize 事件
 * */
function initResizeEvent() {
    const RESIZE_DELAY = 16.7;
    let app = window.SHARED.$root;

    bindEvent(window, 'resize', debounce(() => {
        app.$store.commit('updateHeight', app.isShowWarn);
        app.$store.commit('updateWidth');
        app.$store.commit('updateLeftNavWidth');
        let viewComp = app.$refs.viewComp;

        if (isFunction(viewComp.$options.onResize)) {
            viewComp.$options.onResize.call(viewComp);
        }
    }, RESIZE_DELAY));
}


function initGlobalConst() {
    window.SHARED.CONST = {
        PRE_SALE_PHONE: '400-806-6868',
        AFTER_SALE_PHONE: '400-630-6430',
        SUBSCRIBE_SERVICE_PHONE: '0731-88043168'
    };
}

/**
 * BBC所有的遮罩层统一都用 defer:0 的效果
 * */
function fixBBCMask() {
    let _maskFn = Vue.prototype.$mask;
    Vue.prototype.$mask = function (el, options = {}) {
        let me = this;

        return _maskFn.call(me, el, Object.assign({
            defer: 0
        }, options));
    };
}

/**
 * 页面入口
 */
export function init() {

    initGlobalConst();

    // 初始化 ajax
    Ajax.init();

    // 初始化路由配置
    initRouter();

    // 加载页面主体
    initApp();

    initResizeEvent();

    // 重写 mask
    fixBBCMask();

    Vue.prototype.CSRF = window.SHARED.CSRF;

    document.title = 'AI';

}

beforeInit(init, store);
